package hn.cch.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;

import java.nio.charset.StandardCharsets;

/**
 * HTTP事件处理
 */

public class HttpHandler extends ChannelInboundHandlerAdapter {



    private boolean keepAlive = false;
    private int contentLength = 0;

    private ByteBuf byteBuf = null;
    private String uri = null;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("HttpHandler");

        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;


            keepAlive = HttpUtil.isKeepAlive(httpRequest);

            contentLength = (int) HttpUtil.getContentLength(httpRequest);
            byteBuf = ctx.alloc().heapBuffer(contentLength);


            uri = httpRequest.uri();

            // QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
            // String uriPath = queryStringDecoder.path();
            // logger.info("http uri path : " + uriPath);
            // Map<String, List<String>> params = queryStringDecoder.parameters();
            // if (!params.isEmpty()) {
            //     for (Map.Entry<String, List<String>> param : params.entrySet()) {
            //         String key = param.getKey();
            //         List<String> values = param.getValue();
            //         for (String value : values) {
            //             logger.info("    " + key + "=" + value);
            //         }
            //     }
            // }

            // logger.info("http message header : ");
            // HttpHeaders httpHeaders = httpRequest.headers();
            // if (!httpHeaders.isEmpty()) {
            //     for (Map.Entry<String, String> httpHeader : httpHeaders) {
            //         CharSequence key = httpHeader.getKey();
            //         CharSequence value = httpHeader.getValue();
            //         logger.info("    " + key + "=" + value);
            //     }
            // }


           // HttpMethod httpMethod = httpRequest.method();
           // logger.info("http message method : " + httpMethod.name());
           // if (httpMethod.equals(HttpMethod.GET)){
           //
           //
           // }
           // if (httpMethod.equals(HttpMethod.POST)){
           //
           // }








        }

        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf contentByteBuf = httpContent.content();
            contentByteBuf.readBytes(byteBuf);
            // contentByteBuf.release();


            if (msg instanceof LastHttpContent) {
                byte[] bytes = new byte[contentLength];
                byteBuf.readBytes(bytes);
                byteBuf.release();

                byte[] content = "HelloWorld".getBytes(StandardCharsets.UTF_8);//返回数据

                DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK, Unpooled.wrappedBuffer(content));

                defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN)
                        .setInt(HttpHeaderNames.CONTENT_LENGTH, defaultFullHttpResponse.content().readableBytes());

                if (!keepAlive) {
                    defaultFullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
                }
                ChannelFuture channelFuture = ctx.write(defaultFullHttpResponse);
                if (!keepAlive) {
                    channelFuture.addListener(ChannelFutureListener.CLOSE);
                }


            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}

